package cn.wolfcode.rbac.web.controller;


import cn.wolfcode.rbac.domain.Customer;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.domain.NormalCustomer;
import cn.wolfcode.rbac.domain.SystemDictionaryItem;
import cn.wolfcode.rbac.query.NormalCustomerQueryObject;
import cn.wolfcode.rbac.service.ICustomerService;
import cn.wolfcode.rbac.service.INormalCustomerService;
import cn.wolfcode.rbac.service.ISystemDictionaryItemService;
import cn.wolfcode.rbac.util.JsonResult;
import cn.wolfcode.rbac.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/normalCustomer")
public class NormalCustomerController {
    @Autowired
    private INormalCustomerService service;
    @Autowired
    private ISystemDictionaryItemService systemDictionaryItemService;
    @Autowired
    private ICustomerService customerService;
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") NormalCustomerQueryObject qo) {
        Employee employee = UserContext.getCurrentUser();
        Subject subject = SecurityUtils.getSubject();

        if (!(subject.hasRole("MARKET_MANAGER") || subject.hasRole("admin"))) {
            qo.setSellerId(employee.getId());
        }
        PageInfo result = service.query(qo);
        model.addAttribute("result", result);
        List<SystemDictionaryItem> course = systemDictionaryItemService.selectByParentSn("subject");
        model.addAttribute("course", course);
        List<Customer> potentialCustomers = customerService.selectByStatus(0L);
        model.addAttribute("potentialCustomers", potentialCustomers);

        return "normalCustomer/list";
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(NormalCustomer u) {
        try {
            service.saveOrUpdate(u);
            return new JsonResult("成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(e.getMessage(), false);
        }
    }

}
